import $axios from "axios";
import store from '../store/store'
import { Message } from "element-ui";
window.ccmsApi = "/ccmsApi"; //中煤Api
window.loginApi = "/loginApi"; //登录Api
window.baseApi = "/baseApi"; //基础Api

const axios = $axios.create();
//超时时间
axios.defaults.timeout = 60 * 1000;

//允许缓存
axios.defaults.withCredentials = true;

//通用头部
axios.defaults.headers.common["Content-Type"] =
  "application/json;charset=utf-8";

// 响应拦截（配置请求回来的信息）
axios.interceptors.response.use(
  function(response) {
    //如果是baseApi
    if (response.config.url.indexOf(window.baseApi) === 0) {
      //取消axios为response包的壳
      response = response.data;
      let code = String(response.code);
      //操作成功放行
      if(code==='10000'){

      }
      //无Token,Token异常,其他地方登录 需要重定向
      else if(code==='10001'||code==='10002'||code==='10003'){
        store.commit('cancel');
        router.push({ path: "/login" });
        Message.error({ message: `${response.msg}`, duration: 3000 });
      }
      //税率模板被使用警告信息
      else if(code ==='30000'){

      }
      else{
        Message.warning({ message: `${response.msg}`, duration: 3000 });
      }
    } else response = response.data;
    // 处理响应数据
    return response;
  },
  function(error) {
    if (error) {
        if (error.response&&error.response.status == "401") {
            Message.error({
            message: error.response.data.message || "登录失败，用户名或密码错误",
            duration: 3000
            });
            localStorage.clear();
            router.push({ path: "/login" });
            return;
        }
        Message.error({ message: `error:${error}`, duration: 3000 });
    }
    // 处理响应失败
    return Promise.reject(error);
  }
);
export default axios;
